#include <stdio.h>
#include <string.h>
#include "parse.h"
// void split_part(char *part)
// {
//     char *word = strtok(part, " ");
//     while (word != NULL)
//     {
//         word = strtok(NULL, " ");
//     }
//     return 0;
// }

// int split_line(char *line)
// {
//     int cmdc = 0;
//     char *save;
//     char *part = strtok_r(line, "|", &save);
//     while (part != NULL)
//     {
//         part = strtok_r(NULL, "|", &save);
//         cmdc++;
//     }
//     return cmdc;
// }
int parse_pipe_cmd(char *line, struct cmd *cmdv)
{
    int cmdc = 0;
    char *save;
    char *cmd = strtok_r(line, "|", &save);
    while (cmd != NULL)
    {
        parse_cmd(cmd, &cmdv[cmdc]);
        cmdc++;
        cmd = strtok_r(NULL, "|", &save);
    }
    return cmdc;
}
void parse_cmd(char *line, struct cmd *cmd)
{
    cmd->argc = 0;
    cmd->input = NULL;
    cmd->output = NULL;
    char *arg = strtok(line, " ");
    while (arg != NULL)
    {
        switch (arg[0])
        {
        case '>':
            cmd->output = arg + 1;
            break;
        case '<':
            cmd->input = arg + 1;
            break;
        default:
            cmd->argv[cmd->argc] = arg;
            cmd->argc++;
            // break;
        }
        arg = strtok(NULL, " ");
    }
    cmd->argv[cmd->argc] = NULL;
}

void dump_cmd(struct cmd *cmd) // debug
{
    printf("argc = %d\n", cmd->argc);
    for (int i = 0; i < cmd->argc; i++)
        printf("argv[%d] = (%s)\n", i, cmd->argv[i]);
    printf("input = (%s)\n", cmd->input);
    printf("output = (%s)\n", cmd->output);
}

void dump_pipe_cmd(int cmdc, struct cmd *cmdv)
{
    int i;

    printf("pipe cmd, cmdc = %d\n", cmdc);
    for (i = 0; i < cmdc; i++)
    {
        struct cmd *cmd = cmdv + i;
        dump_cmd(cmd);
    }
}
